// 像素生存者游戏 - 核心游戏逻辑
class PixelSurvivor extends Phaser.Scene {
    constructor() {
        super({ key: 'PixelSurvivor' });

        // 游戏状态
        this.player = null;
        this.enemies = null;
        this.bullets = null;
        this.wave = 1;
        this.enemiesKilled = 0;
        this.gameTime = 0;

        // 玩家属性
        this.playerStats = {
            health: 100,
            maxHealth: 100,
            damage: 10,
            fireRate: 500, // 毫秒
            speed: 150,
            range: 200,
            critChance: 0.1, // 暴击率
            critDamage: 2.0, // 暴击倍数
            piercing: 0, // 穿透数量
            multishot: 1 // 多重射击
        };

        this.lastFired = 0;
        this.weapons = ['pistol']; // 当前武器
        this.isUpgrading = false;
        this.upgradeOptions = [];

        // Boss系统
        this.isBossWave = false;
        this.currentBoss = null;
        this.enemyBullets = null;
        this.bossesKilled = 0;

        // 粒子系统
        this.particles = null;
        this.playerTrail = [];

        // 道具系统
        this.pickups = null;
        this.experiencePoints = 0;
        this.playerLevel = 1;
        this.expToNextLevel = 100; // 升级所需经验
        this.totalExpNeeded = 100; // 当前等级总经验需求
    }

    preload() {
        // 创建简单的像素艺术精灵
        this.createPixelSprites();
    }

    createPixelSprites() {
        // 玩家精灵 (绿色方块)
        this.add.graphics()
            .fillStyle(0x00ff00)
            .fillRect(0, 0, 16, 16)
            .generateTexture('player', 16, 16);

        // 不同类型敌人精灵
        this.add.graphics()
            .fillStyle(0xff0000)
            .fillRect(0, 0, 12, 12)
            .generateTexture('enemy', 12, 12);

        // 快速敌人 (橙色小方块)
        this.add.graphics()
            .fillStyle(0xff8800)
            .fillRect(0, 0, 8, 8)
            .generateTexture('fast_enemy', 8, 8);

        // 坦克敌人 (深红色大方块)
        this.add.graphics()
            .fillStyle(0x880000)
            .fillRect(0, 0, 18, 18)
            .generateTexture('tank_enemy', 18, 18);

        // Boss敌人 (紫色巨大方块)
        this.add.graphics()
            .fillStyle(0x8800ff)
            .fillRect(0, 0, 32, 32)
            .generateTexture('boss_enemy', 32, 32);

        // 敌人子弹
        this.add.graphics()
            .fillStyle(0xff4444)
            .fillRect(0, 0, 3, 3)
            .generateTexture('enemy_bullet', 3, 3);

        // 不同类型子弹
        this.add.graphics()
            .fillStyle(0xffff00)
            .fillRect(0, 0, 4, 4)
            .generateTexture('bullet', 4, 4);

        this.add.graphics()
            .fillStyle(0x00ffff)
            .fillRect(0, 0, 6, 6)
            .generateTexture('shotgun_bullet', 6, 6);

        this.add.graphics()
            .fillStyle(0xff00ff)
            .fillRect(0, 0, 8, 2)
            .generateTexture('rifle_bullet', 8, 2);

        // 激光武器子弹
        this.add.graphics()
            .fillStyle(0x00ff88)
            .fillRect(0, 0, 12, 3)
            .generateTexture('laser_bullet', 12, 3);

        // 火箭弹
        this.add.graphics()
            .fillStyle(0xff4400)
            .fillRect(0, 0, 8, 8)
            .generateTexture('rocket', 8, 8);

        // 电击子弹
        this.add.graphics()
            .fillStyle(0x88ffff)
            .fillCircle(3, 3, 3)
            .generateTexture('electric_bullet', 6, 6);

        // 升级UI背景
        this.add.graphics()
            .fillStyle(0x000000, 0.8)
            .fillRect(0, 0, 800, 600)
            .generateTexture('upgrade_bg', 800, 600);

        // 粒子效果纹理
        this.add.graphics()
            .fillStyle(0xffff00)
            .fillCircle(2, 2, 2)
            .generateTexture('spark', 4, 4);

        this.add.graphics()
            .fillStyle(0xff0000)
            .fillCircle(3, 3, 3)
            .generateTexture('blood', 6, 6);

        this.add.graphics()
            .fillStyle(0x00ff00)
            .fillCircle(2, 2, 2)
            .generateTexture('trail', 4, 4);

        // 道具精灵
        this.add.graphics()
            .fillStyle(0x00ffff)
            .fillCircle(4, 4, 4)
            .generateTexture('exp_gem', 8, 8);

        this.add.graphics()
            .fillStyle(0xff0080)
            .fillRect(0, 0, 10, 10)
            .generateTexture('health_pack', 10, 10);

        this.add.graphics()
            .fillStyle(0xffd700)
            .fillRect(0, 0, 12, 8)
            .generateTexture('power_up', 12, 8);

        // 爆炸效果
        this.add.graphics()
            .fillStyle(0xff6b35)
            .fillCircle(8, 8, 8)
            .generateTexture('explosion', 16, 16);

        // 血条背景
        this.add.graphics()
            .fillStyle(0x333333)
            .fillRect(0, 0, 20, 4)
            .generateTexture('healthbar_bg', 20, 4);

        // 血条前景
        this.add.graphics()
            .fillStyle(0xff0000)
            .fillRect(0, 0, 20, 4)
            .generateTexture('healthbar_fg', 20, 4);
    }

    create() {
        // 创建按钮背景纹理（用于游戏结束菜单）
        this.add.graphics()
            .fillStyle(0x3498db)
            .fillRect(0, 0, 200, 50)
            .lineStyle(2, 0xffffff)
            .strokeRect(0, 0, 200, 50)
            .generateTexture('button_bg', 200, 50);
            
        // 创建玩家
        this.player = this.physics.add.sprite(400, 300, 'player');
        this.player.setCollideWorldBounds(true);

        // 创建组
        this.enemies = this.physics.add.group();
        this.bullets = this.physics.add.group();
        this.enemyBullets = this.physics.add.group();
        this.pickups = this.physics.add.group();

        // 创建粒子系统
        this.particles = this.add.particles(0, 0, 'spark', {
            scale: { start: 0.5, end: 0 },
            speed: { min: 50, max: 100 },
            lifespan: 300,
            quantity: 0
        });

        this.bloodParticles = this.add.particles(0, 0, 'blood', {
            scale: { start: 0.8, end: 0 },
            speed: { min: 30, max: 80 },
            lifespan: 500,
            quantity: 0
        });

        this.trailParticles = this.add.particles(0, 0, 'trail', {
            scale: { start: 0.3, end: 0 },
            speed: { min: 10, max: 30 },
            lifespan: 200,
            quantity: 0,
            alpha: { start: 0.6, end: 0 }
        });

        // 碰撞检测
        this.physics.add.overlap(this.bullets, this.enemies, this.hitEnemy, null, this);
        this.physics.add.overlap(this.player, this.enemies, this.playerHit, null, this);
        this.physics.add.overlap(this.player, this.enemyBullets, this.playerHitByBullet, null, this);
        this.physics.add.overlap(this.player, this.pickups, this.collectPickup, null, this);

        // 键盘控制
        this.cursors = this.input.keyboard.createCursorKeys();
        this.wasd = this.input.keyboard.addKeys('W,S,A,D');

        // UI文本
        this.waveText = this.add.text(16, 16, `波次: ${this.wave}`, {
            fontSize: '16px',
            fill: '#ffffff'
        });

        this.healthText = this.add.text(16, 40, `生命: ${this.playerStats.health}`, {
            fontSize: '16px',
            fill: '#ffffff'
        });

        // 武器信息显示
        this.weaponText = this.add.text(16, 64, `武器: ${this.weapons.join(', ')}`, {
            fontSize: '16px',
            fill: '#ffffff'
        });

        // 经验值显示
        this.expText = this.add.text(16, 88, `等级: ${this.playerLevel} (${this.experiencePoints}/${this.expToNextLevel})`, {
            fontSize: '16px',
            fill: '#00ffff'
        });
        
        // 经验条
        this.expBarBg = this.add.rectangle(400, 580, 700, 10, 0x333333).setOrigin(0.5);
        this.expBar = this.add.rectangle(400, 580, 700, 8, 0x00ffff).setOrigin(0.5);
        this.expBar.scaleX = 0;

        // 开始生成敌人
        this.spawnEnemyTimer = this.time.addEvent({
            delay: 2000,
            callback: this.spawnEnemy,
            callbackScope: this,
            loop: true
        });
    }

    update(time, delta) {
        this.gameTime += delta;

        // 如果在升级菜单中，不更新游戏逻辑
        if (this.isUpgrading) {
            return;
        }

        // 玩家移动
        this.handlePlayerMovement();

        // 自动射击
        this.handleAutoFire(time);

        // 敌人AI
        this.updateEnemies();

        // 清理超出边界的子弹
        this.bullets.children.entries.forEach(bullet => {
            if (bullet.x < 0 || bullet.x > 800 || bullet.y < 0 || bullet.y > 600) {
                bullet.destroy();
            }
        });
        
        // 经验球吸引效果
        this.pickups.children.entries.forEach(pickup => {
            if (pickup.pickupType === 'exp_gem') {
                const distance = Phaser.Math.Distance.Between(
                    this.player.x, this.player.y,
                    pickup.x, pickup.y
                );
                
                // 当玩家靠近时自动吸引
                if (distance < 150) {
                    const angle = Phaser.Math.Angle.Between(
                        pickup.x, pickup.y,
                        this.player.x, this.player.y
                    );
                    
                    // 距离越近，吸引速度越快
                    const speed = 150 + (150 - distance);
                    
                    pickup.setVelocity(
                        Math.cos(angle) * speed,
                        Math.sin(angle) * speed
                    );
                }
            }
        });
    }

    handlePlayerMovement() {
        const speed = this.playerStats.speed;
        let isMoving = false;

        // 重置速度
        this.player.setVelocity(0);

        // WASD 或 方向键控制
        if (this.cursors.left.isDown || this.wasd.A.isDown) {
            this.player.setVelocityX(-speed);
            isMoving = true;
        } else if (this.cursors.right.isDown || this.wasd.D.isDown) {
            this.player.setVelocityX(speed);
            isMoving = true;
        }

        if (this.cursors.up.isDown || this.wasd.W.isDown) {
            this.player.setVelocityY(-speed);
            isMoving = true;
        } else if (this.cursors.down.isDown || this.wasd.S.isDown) {
            this.player.setVelocityY(speed);
            isMoving = true;
        }

        // 玩家移动尾迹效果
        if (isMoving && Math.random() < 0.3) {
            this.trailParticles.emitParticleAt(this.player.x, this.player.y, 1);
        }
    }

    handleAutoFire(time) {
        if (time - this.lastFired > this.playerStats.fireRate) {
            const nearestEnemy = this.findNearestEnemy();
            if (nearestEnemy) {
                this.fireAtTarget(nearestEnemy);
                this.lastFired = time;
            }
        }
    }

    findNearestEnemy() {
        let nearest = null;
        let minDistance = this.playerStats.range;

        this.enemies.children.entries.forEach(enemy => {
            const distance = Phaser.Math.Distance.Between(
                this.player.x, this.player.y,
                enemy.x, enemy.y
            );

            if (distance < minDistance) {
                minDistance = distance;
                nearest = enemy;
            }
        });

        return nearest;
    }

    fireAtTarget(target) {
        // 根据武器类型射击
        this.weapons.forEach(weapon => {
            this.fireWeapon(weapon, target);
        });
    }

    fireWeapon(weaponType, target) {
        const angle = Phaser.Math.Angle.Between(
            this.player.x, this.player.y,
            target.x, target.y
        );

        switch (weaponType) {
            case 'pistol':
                this.createBullet('bullet', angle, 300, this.playerStats.damage);
                break;
            case 'shotgun':
                // 散弹枪 - 3发子弹扇形射击
                for (let i = -1; i <= 1; i++) {
                    this.createBullet('shotgun_bullet', angle + (i * 0.3), 250, this.playerStats.damage * 0.7);
                }
                break;
            case 'rifle':
                this.createBullet('rifle_bullet', angle, 400, this.playerStats.damage * 1.5);
                break;
            case 'machinegun':
                // 机枪 - 多重射击
                for (let i = 0; i < this.playerStats.multishot; i++) {
                    setTimeout(() => {
                        this.createBullet('bullet', angle + (Math.random() - 0.5) * 0.2, 350, this.playerStats.damage);
                    }, i * 50);
                }
                break;
            case 'laser':
                // 激光武器 - 穿透所有敌人
                this.createLaserBullet('laser_bullet', angle, 500, this.playerStats.damage * 1.2);
                break;
            case 'rocket':
                // 火箭发射器 - 范围伤害
                this.createRocketBullet('rocket', angle, 200, this.playerStats.damage * 2);
                break;
            case 'electric':
                // 电击枪 - 连锁伤害
                this.createElectricBullet('electric_bullet', angle, 300, this.playerStats.damage * 0.8);
                break;
        }
    }

    createBullet(bulletType, angle, speed, damage) {
        const bullet = this.bullets.create(this.player.x, this.player.y, bulletType);
        bullet.setVelocity(
            Math.cos(angle) * speed,
            Math.sin(angle) * speed
        );
        bullet.damage = damage;
        bullet.piercing = this.playerStats.piercing;
        bullet.piercedEnemies = 0;

        // 子弹发射火花效果
        this.particles.emitParticleAt(this.player.x, this.player.y, 3);
    }

    // 新武器类型的子弹创建函数
    createLaserBullet(bulletType, angle, speed, damage) {
        const bullet = this.bullets.create(this.player.x, this.player.y, bulletType);
        bullet.setVelocity(
            Math.cos(angle) * speed,
            Math.sin(angle) * speed
        );
        bullet.damage = damage;
        bullet.piercing = 999; // 激光穿透所有敌人
        bullet.piercedEnemies = 0;
        bullet.weaponType = 'laser';

        // 激光特效
        this.particles.emitParticleAt(this.player.x, this.player.y, 5);
    }

    createRocketBullet(bulletType, angle, speed, damage) {
        const bullet = this.bullets.create(this.player.x, this.player.y, bulletType);
        bullet.setVelocity(
            Math.cos(angle) * speed,
            Math.sin(angle) * speed
        );
        bullet.damage = damage;
        bullet.piercing = 0; // 火箭不穿透
        bullet.piercedEnemies = 0;
        bullet.weaponType = 'rocket';

        // 火箭尾迹
        this.trailParticles.emitParticleAt(this.player.x, this.player.y, 3);
    }

    createElectricBullet(bulletType, angle, speed, damage) {
        const bullet = this.bullets.create(this.player.x, this.player.y, bulletType);
        bullet.setVelocity(
            Math.cos(angle) * speed,
            Math.sin(angle) * speed
        );
        bullet.damage = damage;
        bullet.piercing = this.playerStats.piercing;
        bullet.piercedEnemies = 0;
        bullet.weaponType = 'electric';

        // 电击特效
        this.particles.emitParticleAt(this.player.x, this.player.y, 4);
    }

    spawnEnemy() {
        // 检查是否为Boss波次 (每5波)
        if (this.wave % 5 === 0 && !this.isBossWave && !this.currentBoss) {
            this.spawnBoss();
            return;
        }

        // 普通敌人生成
        if (!this.isBossWave) {
            const side = Phaser.Math.Between(0, 3);
            let x, y;

            switch (side) {
                case 0: // 上
                    x = Phaser.Math.Between(0, 800);
                    y = -20;
                    break;
                case 1: // 右
                    x = 820;
                    y = Phaser.Math.Between(0, 600);
                    break;
                case 2: // 下
                    x = Phaser.Math.Between(0, 800);
                    y = 620;
                    break;
                case 3: // 左
                    x = -20;
                    y = Phaser.Math.Between(0, 600);
                    break;
            }

            // 随机生成不同类型的敌人
            const enemyType = this.getRandomEnemyType();
            const enemy = this.enemies.create(x, y, enemyType.sprite);

            // 设置敌人属性
            enemy.health = enemyType.health + (this.wave * 3);
            enemy.maxHealth = enemy.health;
            enemy.speed = enemyType.speed;
            enemy.damage = enemyType.damage;
            enemy.type = enemyType.name;
            enemy.lastFired = 0;

            // 为敌人添加血条
            this.createEnemyHealthBar(enemy);
        }
    }

    getRandomEnemyType() {
        const enemyTypes = [
            {
                name: 'normal',
                sprite: 'enemy',
                health: 20,
                speed: 50,
                damage: 10
            },
            {
                name: 'fast',
                sprite: 'fast_enemy',
                health: 10,
                speed: 100,
                damage: 8
            },
            {
                name: 'tank',
                sprite: 'tank_enemy',
                health: 60,
                speed: 25,
                damage: 15
            }
        ];

        // 根据波次调整敌人类型概率
        let weights = [60, 25, 15]; // 普通, 快速, 坦克
        if (this.wave > 3) weights = [40, 35, 25];
        if (this.wave > 7) weights = [30, 30, 40];

        const random = Math.random() * 100;
        let cumulative = 0;

        for (let i = 0; i < weights.length; i++) {
            cumulative += weights[i];
            if (random <= cumulative) {
                return enemyTypes[i];
            }
        }

        return enemyTypes[0];
    }

    spawnBoss() {
        this.isBossWave = true;

        // Boss从屏幕中央上方出现
        const boss = this.enemies.create(400, -50, 'boss_enemy');
        boss.health = 200 + (this.wave * 50);
        boss.maxHealth = boss.health;
        boss.speed = 30;
        boss.damage = 25;
        boss.type = 'boss';
        boss.lastFired = 0;
        boss.attackPattern = 0;
        boss.patternTimer = 0;

        this.currentBoss = boss;

        // Boss血条 (更大更显眼)
        this.createBossHealthBar(boss);

        // Boss出现特效
        this.createExplosion(boss.x, boss.y);
        this.cameras.main.shake(500, 0.02);

        // 暂停普通敌人生成
        this.spawnEnemyTimer.paused = true;
    }

    updateEnemies() {
        this.enemies.children.entries.forEach(enemy => {
            if (enemy.type === 'boss') {
                this.updateBoss(enemy);
            } else {
                this.updateNormalEnemy(enemy);
            }

            // 更新敌人血条位置
            if (enemy.healthBar) {
                enemy.healthBar.x = enemy.x - 10;
                enemy.healthBar.y = enemy.y - 20;
                enemy.healthBarBg.x = enemy.x - 10;
                enemy.healthBarBg.y = enemy.y - 20;

                // 更新血条长度
                const healthPercent = enemy.health / enemy.maxHealth;
                enemy.healthBar.scaleX = healthPercent;
            }

            // 更新Boss血条
            if (enemy.type === 'boss' && enemy.bossHealthFg) {
                const healthPercent = enemy.health / enemy.maxHealth;
                enemy.bossHealthFg.scaleX = healthPercent;
            }
        });

        // 清理敌人子弹
        this.enemyBullets.children.entries.forEach(bullet => {
            if (bullet.x < -50 || bullet.x > 850 || bullet.y < -50 || bullet.y > 650) {
                bullet.destroy();
            }
        });
    }

    updateNormalEnemy(enemy) {
        // 普通敌人朝玩家移动
        const angle = Phaser.Math.Angle.Between(
            enemy.x, enemy.y,
            this.player.x, this.player.y
        );

        const speed = enemy.speed + (this.wave * 3);
        enemy.setVelocity(
            Math.cos(angle) * speed,
            Math.sin(angle) * speed
        );
    }

    updateBoss(boss) {
        boss.patternTimer += 16; // 假设60FPS

        // Boss移动模式
        const playerDistance = Phaser.Math.Distance.Between(
            boss.x, boss.y, this.player.x, this.player.y
        );

        if (playerDistance > 150) {
            // 靠近玩家
            const angle = Phaser.Math.Angle.Between(
                boss.x, boss.y, this.player.x, this.player.y
            );
            boss.setVelocity(
                Math.cos(angle) * boss.speed,
                Math.sin(angle) * boss.speed
            );
        } else {
            // 保持距离，环绕移动
            const angle = Phaser.Math.Angle.Between(
                boss.x, boss.y, this.player.x, this.player.y
            ) + Math.PI / 2;
            boss.setVelocity(
                Math.cos(angle) * boss.speed * 0.7,
                Math.sin(angle) * boss.speed * 0.7
            );
        }

        // Boss攻击模式
        if (boss.patternTimer > 2000) { // 每2秒切换攻击模式
            boss.attackPattern = (boss.attackPattern + 1) % 3;
            boss.patternTimer = 0;
        }

        // 执行攻击
        if (this.time.now - boss.lastFired > 800) {
            this.bossAttack(boss);
            boss.lastFired = this.time.now;
        }
    }

    bossAttack(boss) {
        const playerAngle = Phaser.Math.Angle.Between(
            boss.x, boss.y, this.player.x, this.player.y
        );

        switch (boss.attackPattern) {
            case 0: // 单发精准射击
                this.createEnemyBullet(boss.x, boss.y, playerAngle, 200, 25);
                break;

            case 1: // 扇形射击
                for (let i = -2; i <= 2; i++) {
                    this.createEnemyBullet(
                        boss.x, boss.y,
                        playerAngle + (i * 0.3),
                        180, 15
                    );
                }
                break;

            case 2: // 环形射击
                for (let i = 0; i < 8; i++) {
                    const angle = (Math.PI * 2 / 8) * i;
                    this.createEnemyBullet(boss.x, boss.y, angle, 150, 20);
                }
                break;
        }
    }

    createEnemyBullet(x, y, angle, speed, damage) {
        const bullet = this.enemyBullets.create(x, y, 'enemy_bullet');
        bullet.setVelocity(
            Math.cos(angle) * speed,
            Math.sin(angle) * speed
        );
        bullet.damage = damage;
    }

    hitEnemy(bullet, enemy) {
        // 计算伤害（包含暴击）
        let damage = bullet.damage || this.playerStats.damage;
        const isCrit = Math.random() < this.playerStats.critChance;
        if (isCrit) {
            damage *= this.playerStats.critDamage;
            // 暴击视觉效果
            this.createDamageText(enemy.x, enemy.y, Math.floor(damage), true);
        } else {
            this.createDamageText(enemy.x, enemy.y, Math.floor(damage), false);
        }

        enemy.health -= damage;

        // 穿透逻辑
        bullet.piercedEnemies = (bullet.piercedEnemies || 0) + 1;
        if (bullet.piercedEnemies > bullet.piercing) {
            bullet.destroy();
        }

        if (enemy.health <= 0) {
            // 死亡爆炸效果和血液粒子
            this.createExplosion(enemy.x, enemy.y);
            this.bloodParticles.emitParticleAt(enemy.x, enemy.y, 5);

            // 清理敌人血条
            if (enemy.healthBar) {
                enemy.healthBar.destroy();
                enemy.healthBarBg.destroy();
            }

            // 掉落道具
            this.dropPickup(enemy.x, enemy.y, enemy.type);

            // Boss死亡处理
            if (enemy.type === 'boss') {
                this.handleBossDeath(enemy);
            } else {
                this.enemiesKilled++;
                
                // 检查成就
                this.checkAchievements();

                // 每杀死10个敌人触发升级
                if (this.enemiesKilled % 10 === 0) {
                    this.wave++;
                    this.waveText.setText(`波次: ${this.wave}`);
                    this.showUpgradeMenu();
                }
            }

            enemy.destroy();
        }
    }

    playerHit(player, enemy) {
        this.playerStats.health -= enemy.damage || 10;
        this.healthText.setText(`生命: ${this.playerStats.health}`);

        // 清理敌人血条
        if (enemy.healthBar) {
            enemy.healthBar.destroy();
            enemy.healthBarBg.destroy();
        }

        enemy.destroy();

        // 受伤闪烁效果
        this.player.setTint(0xff0000);
        this.time.delayedCall(200, () => {
            this.player.clearTint();
        });

        if (this.playerStats.health <= 0) {
            this.gameOver();
        }
    }

    playerHitByBullet(player, bullet) {
        this.playerStats.health -= bullet.damage || 15;
        this.healthText.setText(`生命: ${this.playerStats.health}`);

        bullet.destroy();

        // 受伤闪烁效果
        this.player.setTint(0xff0000);
        this.time.delayedCall(200, () => {
            this.player.clearTint();
        });

        if (this.playerStats.health <= 0) {
            this.gameOver();
        }
    }

    createEnemyHealthBar(enemy) {
        // 血条背景
        enemy.healthBarBg = this.add.image(enemy.x - 10, enemy.y - 20, 'healthbar_bg');
        enemy.healthBarBg.setOrigin(0, 0.5);

        // 血条前景
        enemy.healthBar = this.add.image(enemy.x - 10, enemy.y - 20, 'healthbar_fg');
        enemy.healthBar.setOrigin(0, 0.5);
    }

    createBossHealthBar(boss) {
        // Boss血条 - 屏幕顶部
        const bossHealthBg = this.add.rectangle(400, 30, 400, 20, 0x333333);
        bossHealthBg.setStrokeStyle(2, 0xffffff);

        const bossHealthFg = this.add.rectangle(400, 30, 400, 16, 0xff0000);

        boss.bossHealthBg = bossHealthBg;
        boss.bossHealthFg = bossHealthFg;

        // Boss名称
        this.add.text(400, 50, `Boss - 波次 ${this.wave}`, {
            fontSize: '16px',
            fill: '#ffffff'
        }).setOrigin(0.5);
    }

    handleBossDeath(boss) {
        // 清理Boss血条
        if (boss.bossHealthBg) {
            boss.bossHealthBg.destroy();
            boss.bossHealthFg.destroy();
        }

        // Boss死亡特效
        this.cameras.main.shake(1000, 0.03);

        // 多重爆炸效果
        for (let i = 0; i < 5; i++) {
            this.time.delayedCall(i * 200, () => {
                const offsetX = (Math.random() - 0.5) * 60;
                const offsetY = (Math.random() - 0.5) * 60;
                this.createExplosion(boss.x + offsetX, boss.y + offsetY);
            });
        }

        // 增加Boss击杀计数
        this.bossesKilled++;
        
        // 检查成就
        this.checkAchievements();

        // 重置Boss状态
        this.isBossWave = false;
        this.currentBoss = null;

        // 恢复普通敌人生成
        this.spawnEnemyTimer.paused = false;

        // 进入下一波并触发升级
        this.wave++;
        this.waveText.setText(`波次: ${this.wave}`);

        // Boss击败奖励 - 额外升级选择
        this.time.delayedCall(1000, () => {
            this.showBossRewardMenu();
        });
    }

    showUpgradeMenu() {
        this.isUpgrading = true;
        this.physics.pause();

        // 创建升级背景
        const upgradeBg = this.add.image(400, 300, 'upgrade_bg').setOrigin(0.5);

        // 升级标题
        const title = this.add.text(400, 150, '选择升级', {
            fontSize: '32px',
            fill: '#ffffff'
        }).setOrigin(0.5);

        // 生成3个随机升级选项
        this.upgradeOptions = this.generateUpgradeOptions();

        // 创建升级选项按钮
        this.upgradeOptions.forEach((option, index) => {
            const y = 250 + (index * 80);

            // 选项背景
            const optionBg = this.add.rectangle(400, y, 600, 60, 0x34495e)
                .setStrokeStyle(2, 0x3498db);

            // 选项文本
            const optionText = this.add.text(400, y, `${option.name}\n${option.description}`, {
                fontSize: '16px',
                fill: '#ffffff',
                align: 'center'
            }).setOrigin(0.5);

            // 点击事件
            optionBg.setInteractive();
            optionBg.on('pointerdown', () => {
                this.selectUpgrade(option);
                // 清理升级UI
                upgradeBg.destroy();
                title.destroy();
                this.upgradeOptions.forEach((_, i) => {
                    const cleanupY = 250 + (i * 80);
                    this.children.getByName(`option_${i}_bg`)?.destroy();
                    this.children.getByName(`option_${i}_text`)?.destroy();
                });
                optionBg.destroy();
                optionText.destroy();
                this.resumeGame();
            });

            optionBg.name = `option_${index}_bg`;
            optionText.name = `option_${index}_text`;
        });
    }

    generateUpgradeOptions() {
        const allUpgrades = [
            {
                name: '增加伤害',
                description: '伤害 +5',
                effect: () => { this.playerStats.damage += 5; }
            },
            {
                name: '提升射速',
                description: '射击间隔 -100ms',
                effect: () => { this.playerStats.fireRate = Math.max(100, this.playerStats.fireRate - 100); }
            },
            {
                name: '增加生命值',
                description: '最大生命值 +20，回复满血',
                effect: () => {
                    this.playerStats.maxHealth += 20;
                    this.playerStats.health = this.playerStats.maxHealth;
                    this.healthText.setText(`生命: ${this.playerStats.health}`);
                }
            },
            {
                name: '提升移动速度',
                description: '移动速度 +30',
                effect: () => { this.playerStats.speed += 30; }
            },
            {
                name: '增加射程',
                description: '射击范围 +50',
                effect: () => { this.playerStats.range += 50; }
            },
            {
                name: '暴击强化',
                description: '暴击率 +10%',
                effect: () => { this.playerStats.critChance += 0.1; }
            },
            {
                name: '穿透子弹',
                description: '子弹穿透 +1',
                effect: () => { this.playerStats.piercing += 1; }
            },
            {
                name: '获得散弹枪',
                description: '添加散弹枪武器',
                effect: () => {
                    if (!this.weapons.includes('shotgun')) {
                        this.weapons.push('shotgun');
                        this.weaponText.setText(`武器: ${this.weapons.join(', ')}`);
                    }
                }
            },
            {
                name: '获得步枪',
                description: '添加高伤害步枪',
                effect: () => {
                    if (!this.weapons.includes('rifle')) {
                        this.weapons.push('rifle');
                        this.weaponText.setText(`武器: ${this.weapons.join(', ')}`);
                    }
                }
            },
            {
                name: '获得机枪',
                description: '添加高射速机枪',
                effect: () => {
                    if (!this.weapons.includes('machinegun')) {
                        this.weapons.push('machinegun');
                        this.weaponText.setText(`武器: ${this.weapons.join(', ')}`);
                    }
                }
            }
        ];

        // 随机选择3个不同的升级
        const shuffled = Phaser.Utils.Array.Shuffle([...allUpgrades]);
        return shuffled.slice(0, 3);
    }

    selectUpgrade(upgrade) {
        upgrade.effect();
    }

    resumeGame() {
        this.isUpgrading = false;
        this.physics.resume();
    }

    createDamageText(x, y, damage, isCrit) {
        const color = isCrit ? '#ffff00' : '#ffffff';
        const fontSize = isCrit ? '20px' : '16px';

        const damageText = this.add.text(x, y, damage.toString(), {
            fontSize: fontSize,
            fill: color,
            fontWeight: 'bold'
        }).setOrigin(0.5);

        // 伤害数字动画
        this.tweens.add({
            targets: damageText,
            y: y - 30,
            alpha: 0,
            duration: 800,
            ease: 'Power2',
            onComplete: () => {
                damageText.destroy();
            }
        });
    }

    createExplosion(x, y) {
        const explosion = this.add.image(x, y, 'explosion');

        // 爆炸动画
        this.tweens.add({
            targets: explosion,
            scaleX: 2,
            scaleY: 2,
            alpha: 0,
            duration: 300,
            ease: 'Power2',
            onComplete: () => {
                explosion.destroy();
            }
        });

        // 屏幕震动效果
        this.cameras.main.shake(100, 0.01);
    }

    showBossRewardMenu() {
        this.isUpgrading = true;
        this.physics.pause();

        // 创建升级背景
        const upgradeBg = this.add.image(400, 300, 'upgrade_bg').setOrigin(0.5);

        // Boss击败标题
        const title = this.add.text(400, 120, 'Boss击败!', {
            fontSize: '36px',
            fill: '#ffff00'
        }).setOrigin(0.5);

        const subtitle = this.add.text(400, 160, '选择特殊奖励', {
            fontSize: '24px',
            fill: '#ffffff'
        }).setOrigin(0.5);

        // 生成Boss奖励选项
        const bossRewards = this.generateBossRewards();

        // 创建奖励选项按钮
        bossRewards.forEach((reward, index) => {
            const y = 230 + (index * 90);

            // 选项背景 (金色边框)
            const optionBg = this.add.rectangle(400, y, 650, 70, 0x2c3e50)
                .setStrokeStyle(3, 0xffd700);

            // 选项文本
            const optionText = this.add.text(400, y, `${reward.name}\n${reward.description}`, {
                fontSize: '18px',
                fill: '#ffffff',
                align: 'center'
            }).setOrigin(0.5);

            // 点击事件
            optionBg.setInteractive();
            optionBg.on('pointerdown', () => {
                this.selectUpgrade(reward);
                // 清理UI
                upgradeBg.destroy();
                title.destroy();
                subtitle.destroy();
                bossRewards.forEach((_, i) => {
                    this.children.getByName(`boss_option_${i}_bg`)?.destroy();
                    this.children.getByName(`boss_option_${i}_text`)?.destroy();
                });
                optionBg.destroy();
                optionText.destroy();
                this.resumeGame();
            });

            optionBg.name = `boss_option_${index}_bg`;
            optionText.name = `boss_option_${index}_text`;
        });
    }

    generateBossRewards() {
        const bossRewards = [
            {
                name: '🔥 火焰强化',
                description: '所有武器伤害 +15，获得燃烧效果',
                effect: () => {
                    this.playerStats.damage += 15;
                    this.playerStats.burnDamage = true;
                }
            },
            {
                name: '⚡ 闪电射速',
                description: '射击间隔 -200ms，获得连锁闪电',
                effect: () => {
                    this.playerStats.fireRate = Math.max(50, this.playerStats.fireRate - 200);
                    this.playerStats.chainLightning = true;
                }
            },
            {
                name: '🛡️ 钢铁之躯',
                description: '最大生命值 +50，获得护甲效果',
                effect: () => {
                    this.playerStats.maxHealth += 50;
                    this.playerStats.health = this.playerStats.maxHealth;
                    this.playerStats.armor = 5;
                    this.healthText.setText(`生命: ${this.playerStats.health}`);
                }
            },
            {
                name: '💥 爆炸专家',
                description: '子弹穿透 +3，死亡爆炸伤害',
                effect: () => {
                    this.playerStats.piercing += 3;
                    this.playerStats.explosiveKills = true;
                }
            },
            {
                name: '🎯 精准大师',
                description: '暴击率 +25%，暴击伤害 +1.0倍',
                effect: () => {
                    this.playerStats.critChance += 0.25;
                    this.playerStats.critDamage += 1.0;
                }
            },
            {
                name: '🚀 获得激光武器',
                description: '添加穿透激光武器',
                effect: () => {
                    if (!this.weapons.includes('laser')) {
                        this.weapons.push('laser');
                        this.weaponText.setText(`武器: ${this.weapons.join(', ')}`);
                    }
                }
            },
            {
                name: '💣 获得火箭发射器',
                description: '添加范围伤害火箭',
                effect: () => {
                    if (!this.weapons.includes('rocket')) {
                        this.weapons.push('rocket');
                        this.weaponText.setText(`武器: ${this.weapons.join(', ')}`);
                    }
                }
            },
            {
                name: '⚡ 获得电击枪',
                description: '添加连锁伤害电击枪',
                effect: () => {
                    if (!this.weapons.includes('electric')) {
                        this.weapons.push('electric');
                        this.weaponText.setText(`武器: ${this.weapons.join(', ')}`);
                    }
                }
            }
        ];

        // 随机选择3个Boss奖励
        const shuffled = Phaser.Utils.Array.Shuffle([...bossRewards]);
        return shuffled.slice(0, 3);
    }

    gameOver() {
        // 保存成就
        this.checkAchievements();
        
        // 游戏结束UI
        const gameOverBg = this.add.rectangle(400, 300, 500, 400, 0x000000, 0.8)
            .setStrokeStyle(4, 0xff0000);
            
        this.add.text(400, 200, '游戏结束!', {
            fontSize: '32px',
            fill: '#ff0000',
            fontWeight: 'bold'
        }).setOrigin(0.5);

        this.add.text(400, 250, `存活波次: ${this.wave}`, {
            fontSize: '20px',
            fill: '#ffffff'
        }).setOrigin(0.5);

        this.add.text(400, 280, `击杀敌人: ${this.enemiesKilled}`, {
            fontSize: '20px',
            fill: '#ffffff'
        }).setOrigin(0.5);

        this.add.text(400, 310, `收集经验: ${this.experiencePoints}`, {
            fontSize: '20px',
            fill: '#00ffff'
        }).setOrigin(0.5);
        
        this.add.text(400, 340, `击败Boss: ${this.bossesKilled}`, {
            fontSize: '20px',
            fill: '#ff00ff'
        }).setOrigin(0.5);

        // 返回主菜单按钮
        const menuButton = this.add.image(400, 400, 'button_bg').setOrigin(0.5);
        this.add.text(400, 400, '返回主菜单', {
            fontSize: '18px',
            fill: '#ffffff'
        }).setOrigin(0.5);
        
        // 重新开始按钮
        const restartButton = this.add.image(400, 460, 'button_bg').setOrigin(0.5);
        this.add.text(400, 460, '重新开始', {
            fontSize: '18px',
            fill: '#ffffff'
        }).setOrigin(0.5);
        
        // 按钮交互
        menuButton.setInteractive();
        restartButton.setInteractive();
        
        menuButton.on('pointerover', () => menuButton.setScale(1.1));
        menuButton.on('pointerout', () => menuButton.setScale(1.0));
        restartButton.on('pointerover', () => restartButton.setScale(1.1));
        restartButton.on('pointerout', () => restartButton.setScale(1.0));
        
        menuButton.on('pointerdown', () => {
            this.scene.start('MainMenu');
        });
        
        restartButton.on('pointerdown', () => {
            this.scene.restart();
        });

        this.physics.pause();
        this.spawnEnemyTimer.destroy();
    }

    // 道具掉落系统
    dropPickup(x, y, enemyType) {
        // 根据敌人类型和随机数决定掉落
        const dropChance = Math.random();
        let pickupType = null;

        if (enemyType === 'boss') {
            // Boss必定掉落多个道具
            this.createPickup(x - 20, y, 'exp_gem');
            this.createPickup(x + 20, y, 'health_pack');
            this.createPickup(x, y - 20, 'power_up');
            return;
        }

        // 普通敌人掉落概率
        if (dropChance < 0.7) {
            pickupType = 'exp_gem'; // 70% 经验宝石
        } else if (dropChance < 0.85) {
            pickupType = 'health_pack'; // 15% 血包
        } else if (dropChance < 0.95) {
            pickupType = 'power_up'; // 10% 能量提升
        }
        // 5% 不掉落

        if (pickupType) {
            this.createPickup(x, y, pickupType);
        }
    }

    createPickup(x, y, type) {
        const pickup = this.pickups.create(x, y, type);
        pickup.pickupType = type;
        
        // 经验球不移动，其他道具仍然有随机移动
        if (type !== 'exp_gem') {
            pickup.setVelocity(
                (Math.random() - 0.5) * 100,
                (Math.random() - 0.5) * 100
            );
        }

        // 道具闪烁效果
        this.tweens.add({
            targets: pickup,
            alpha: 0.5,
            duration: 500,
            yoyo: true,
            repeat: -1
        });
        
        // 经验球有吸引效果
        if (type === 'exp_gem') {
            // 添加轻微的上下浮动效果
            this.tweens.add({
                targets: pickup,
                y: y - 5,
                duration: 1000,
                yoyo: true,
                repeat: -1
            });
        }

        // 道具自动消失
        this.time.delayedCall(10000, () => {
            if (pickup && pickup.active) {
                pickup.destroy();
            }
        });
    }

    collectPickup(player, pickup) {
        switch (pickup.pickupType) {
            case 'exp_gem':
                // 增加经验值
                const expGain = 5;
                this.experiencePoints += expGain;
                
                // 检查是否升级
                if (this.experiencePoints >= this.expToNextLevel) {
                    this.levelUp();
                }
                
                // 更新经验条
                const expRatio = this.experiencePoints / this.expToNextLevel;
                this.expBar.scaleX = expRatio;
                
                // 更新经验文本
                this.expText.setText(`等级: ${this.playerLevel} (${this.experiencePoints}/${this.expToNextLevel})`);
                
                // 经验获取特效
                this.particles.emitParticleAt(pickup.x, pickup.y, 3);
                
                // 显示获得的经验值
                this.showFloatingText(pickup.x, pickup.y, `+${expGain} EXP`, '#00ffff');
                break;

            case 'health_pack':
                const healAmount = 30;
                this.playerStats.health = Math.min(
                    this.playerStats.maxHealth,
                    this.playerStats.health + healAmount
                );
                this.healthText.setText(`生命: ${this.playerStats.health}`);

                // 治疗特效
                this.trailParticles.emitParticleAt(pickup.x, pickup.y, 8);
                break;

            case 'power_up':
                // 临时增益效果
                this.applyPowerUp();
                this.particles.emitParticleAt(pickup.x, pickup.y, 5);
                break;
        }

        pickup.destroy();
    }

    applyPowerUp() {
        // 随机选择一个临时增益
        const powerUps = [
            () => {
                // 临时伤害提升
                const oldDamage = this.playerStats.damage;
                this.playerStats.damage *= 2;
                this.time.delayedCall(5000, () => {
                    this.playerStats.damage = oldDamage;
                });
                this.showPowerUpText('伤害翻倍！');
            },
            () => {
                // 临时射速提升
                const oldFireRate = this.playerStats.fireRate;
                this.playerStats.fireRate *= 0.5;
                this.time.delayedCall(5000, () => {
                    this.playerStats.fireRate = oldFireRate;
                });
                this.showPowerUpText('射速翻倍！');
            },
            () => {
                // 临时速度提升
                const oldSpeed = this.playerStats.speed;
                this.playerStats.speed *= 1.5;
                this.time.delayedCall(5000, () => {
                    this.playerStats.speed = oldSpeed;
                });
                this.showPowerUpText('速度提升！');
            }
        ];

        const randomPowerUp = Phaser.Utils.Array.GetRandom(powerUps);
        randomPowerUp();
    }

    showPowerUpText(text) {
        const powerUpText = this.add.text(400, 200, text, {
            fontSize: '24px',
            fill: '#ffd700',
            fontWeight: 'bold'
        }).setOrigin(0.5);

        this.tweens.add({
            targets: powerUpText,
            y: 150,
            alpha: 0,
            duration: 2000,
            ease: 'Power2',
            onComplete: () => {
                powerUpText.destroy();
            }
        });
    }
    
    // 成就系统
    checkAchievements() {
        // 从本地存储加载成就数据
        let achievements = {};
        const savedData = localStorage.getItem('pixelSurvivorAchievements');
        if (savedData) {
            achievements = JSON.parse(savedData);
        }
        
        // 检查波次成就
        if (this.wave >= 5 && !achievements.wave5) {
            achievements.wave5 = true;
            this.showAchievementUnlocked('初级生存者', '存活5波');
        }
        
        if (this.wave >= 10 && !achievements.wave10) {
            achievements.wave10 = true;
            this.showAchievementUnlocked('中级生存者', '存活10波');
        }
        
        if (this.wave >= 20 && !achievements.wave20) {
            achievements.wave20 = true;
            this.showAchievementUnlocked('高级生存者', '存活20波');
        }
        
        // 检查Boss成就
        if (this.bossesKilled >= 1 && !achievements.boss1) {
            achievements.boss1 = true;
            this.showAchievementUnlocked('Boss猎人', '击败第一个Boss');
        }
        
        if (this.bossesKilled >= 3 && !achievements.boss3) {
            achievements.boss3 = true;
            this.showAchievementUnlocked('Boss终结者', '击败3个Boss');
        }
        
        // 检查武器成就
        const allWeapons = ['pistol', 'shotgun', 'rifle', 'machinegun', 'laser', 'rocket', 'electric'];
        const hasAllWeapons = allWeapons.every(weapon => this.weapons.includes(weapon));
        
        if (hasAllWeapons && !achievements.allWeapons) {
            achievements.allWeapons = true;
            this.showAchievementUnlocked('武器收藏家', '获得所有武器');
        }
        
        // 检查击杀成就
        if (this.enemiesKilled >= 100 && !achievements.kills100) {
            achievements.kills100 = true;
            this.showAchievementUnlocked('百人斩', '击杀100个敌人');
        }
        
        if (this.enemiesKilled >= 500 && !achievements.kills500) {
            achievements.kills500 = true;
            this.showAchievementUnlocked('屠夫', '击杀500个敌人');
        }
        
        // 检查经验成就
        if (this.experiencePoints >= 1000 && !achievements.exp1000) {
            achievements.exp1000 = true;
            this.showAchievementUnlocked('经验丰富', '收集1000点经验');
        }
        
        // 保存成就数据
        localStorage.setItem('pixelSurvivorAchievements', JSON.stringify(achievements));
    }
    
    showAchievementUnlocked(title, description) {
        // 创建成就解锁提示
        const achievementBg = this.add.rectangle(400, 100, 400, 80, 0x000000, 0.8)
            .setStrokeStyle(2, 0xffd700);
            
        const achievementTitle = this.add.text(400, 80, '🏆 成就解锁: ' + title, {
            fontSize: '20px',
            fontFamily: 'Arial',
            fill: '#ffd700'
        }).setOrigin(0.5);
        
        const achievementDesc = this.add.text(400, 110, description, {
            fontSize: '16px',
            fontFamily: 'Arial',
            fill: '#ffffff'
        }).setOrigin(0.5);
        
        // 淡出动画
        this.tweens.add({
            targets: [achievementBg, achievementTitle, achievementDesc],
            alpha: 0,
            delay: 3000,
            duration: 1000,
            onComplete: () => {
                achievementBg.destroy();
                achievementTitle.destroy();
                achievementDesc.destroy();
            }
        });
    }
    
    showFloatingText(x, y, text, color = '#ffffff') {
        const floatingText = this.add.text(x, y, text, {
            fontSize: '20px',
            fill: color,
            stroke: '#000000',
            strokeThickness: 2
        }).setOrigin(0.5);
        
        this.tweens.add({
            targets: floatingText,
            y: y - 40,
            alpha: 0,
            duration: 1000,
            ease: 'Power2',
            onComplete: () => {
                floatingText.destroy();
            }
        });
    }
    
    levelUp() {
        this.playerLevel++;
        
        // 计算下一级所需经验 (每级增加50%)
        this.experiencePoints = 0;
        this.totalExpNeeded = Math.floor(this.totalExpNeeded * 1.5);
        this.expToNextLevel = this.totalExpNeeded;
        
        // 更新经验条
        this.expBar.scaleX = 0;
        
        // 更新经验文本
        this.expText.setText(`等级: ${this.playerLevel} (${this.experiencePoints}/${this.expToNextLevel})`);
        
        // 升级特效
        this.cameras.main.flash(500, 0x00ffff);
        this.particles.emitParticleAt(this.player.x, this.player.y, 20);
        
        // 显示升级文本
        this.showFloatingText(this.player.x, this.player.y, `升级! 等级 ${this.playerLevel}`, '#00ff00');
        
        // 升级奖励 - 自动提升属性
        this.playerStats.damage += 2;
        this.playerStats.maxHealth += 10;
        this.playerStats.health = this.playerStats.maxHealth; // 升级时回满血
        this.healthText.setText(`生命: ${this.playerStats.health}`);
        
        // 显示升级菜单
        this.showUpgradeMenu();
    }
    
    returnToMenu() {
        this.scene.start('MainMenu');
    }
}

// 游戏配置
const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    parent: 'gameContainer',
    backgroundColor: '#2c3e50',
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 0 },
            debug: false
        }
    },
    scene: [MainMenu, PixelSurvivor, Achievements, Settings]
};

// 启动游戏
const game = new Phaser.Game(config);
